using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Serialization;
using Awaiter;
using Nsb.Classes;

namespace Yoshi.Classes
{
    [IgnoreNamespace]
    public class FeedData : SavableData
    {
        public const string FeedRx = "feed";

        private static readonly string PartitionKey = Uri.DbPath("feed");
        private readonly string RowKey;
        public List<FeedItem> Feed;

        public FeedData()
        {
            RowKey = Master.Profile.MyId;
        }

        public void WriteToFeedAw(Await awp, string category, string msg)
        {
            Debug.Assert(category != null, "toId != null");
            FeedItem fd = new FeedItem(category, msg);
            Master.Profile.AddToLocalFeed(fd);

            new Await()
                .AddDl(delegate(Await aw) { AppendBlobStringAw(aw, PartitionKey, RowKey, FeedRx, Json.Stringify(fd)); })
                .Commit(awp);
        }

        public void GetFeedAw(Await awp)
        {
            new Await()
                .AddAw(RetrieveBlobStringAw, PartitionKey, RowKey)
                .HandleDl(Exceptions.BlobLoadError, Await.RethrowAw)
                .AddDx(delegate(Await aw)
                       {
                           //Inform.Debug("Loaded feed");
                           string content = CleanListData((string)aw[ResultRx]);
                           Feed = (List<FeedItem>)(aw[ResultRx] != null ? Json.Parse("[" + content + "]") : null);
                       })
                .Commit(awp);
        }

        public void SaveFeedAw(Await awp)
        {
            if (Feed != null)
                new Await()
                    .AddDl(delegate(Await aw) { StoreBlobStringAw(aw, new Dictionary("partitionKey", PartitionKey, "rowKey", RowKey, "rxKey", FeedRx, "content", SimpleList(Feed))); })
                    .Commit(awp);
            else
                awp.Done();
        }

        public void AddToLocalFeed(FeedItem item)
        {
            if (Feed != null)
                Feed.Add(item);
        }

        public void DeleteItem(string itemId)
        {
            if (Feed == null)
                return;
            int cnt = 0;
            foreach (FeedItem i in Feed)
            {
                if (i.id == itemId)
                {
                    Feed.RemoveAt(cnt);
                    CommentData.DeleteCommentAw(Await.AsyncAw,i.id);
                    SaveFeedAw(Await.AsyncAw);
                    break;
                }
                cnt++;
            }
        }

    }
}